<template>
  <view class="content-body">
    <view class="tab">
      <uni-segmented-control :current="current" styleType="text" :values="values" @clickItem="changeitem">
      </uni-segmented-control>
    </view>
    <view class="content">
      <view class="content-view">
        <uni-card v-for="item in orderListing" :border="false">
          <view class="box">
            <view @click="charge(item)">
              <view class="title">{{item.cabinetName}}({{item.binIndex}}号仓)</view>
              <view class="time-box">
                <view class="order-date">
                  <text><text class="labels">订单日期：</text>{{item.createTime || ''}}</text>
                  <text><text class="labels">订单编号：</text>{{item.code || ''}}</text>
                </view>
              </view>

              <view class="billing-mode"><text class="labels">是否收费：</text>
                <text>
                  {{item.isCharge == 1 ? '免费':'收费'}}
                </text>
              </view>

              <view class="billing-mode"><text class="labels">计费模式：</text>{{chargeType[item.chargeType] || ''}}
                <text v-if="item.price !=null">
                  {{`(${item.price}元`}}
                  <text v-if="item.chargeType=='DURATION' || item.chargeType=='按时'">/{{item.unit}}小时)</text>
                  <text v-else>/kW·h 服务费：{{item.serviceFee}}元/kW·h)</text>
                </text>
              </view>
              <!-- <view v-else class="billing-mode">计费模式:
                    免费
                  </view> -->
              <view class="billing-rules">
                <view class="billing-rules-left">
                  <view><text class="labels">开始时间：</text>{{item.startTime || '00:00:00'}}</view>
                  <view><text class="labels">充电状态：</text><text
                      :style="{color:item.status!=30 ? 'red':'#000000'}">{{item.chargingStatusDesc}}</text>
                  </view>
                </view>
                <!-- <view class="billing-rules-left">
                  <view>
                    <text class="labels">充电费用：</text>{{item.totalFee || '0.00'}}元
                  </view>
                  <view v-if="item.occupyCabinetFees"><text class="labels">占仓费用：</text>{{item.occupyCabinetFees}}元</view>
                </view> -->
              </view>

              <view class="order-time">
                <text>已充时长：</text>
                <text>{{`${item.hour || '00'}:${item.minute || '00'}:${item.second || '00'}`}}</text>
              </view>
              <view class="order-time" v-if="item.chargeType== 'QUANTITY'">
                <text class="labels">已充电量：</text>
                <text>{{item.chargingPower || '0.00'}}kW·h</text>
              </view>
            </view>
            <view class="bottom-button" v-if="current == 0">
              <!-- status == -1 订单取消；0 预付待确认 1 订单确认 5 发起充电失败 10 发起充电成功
              11 充电中 12 充电暂停 13 充电结束 22 结算完成 25 订单结算完成 30 订单完结-->
              <!-- 取消订单：0，1，5，10
              发起充电：1
              停止充电：11，12
              开仓取出：11，12，13，22 -->
              <button v-if="item.status == 11 || item.status ==12" type="default" @click="endModal(item,'takeout',0)"
                :class="item.businessState<4?'open':'opens'">停止充电</button>
              <button v-if="item.status ==11 || item.status ==12 || item.status ==13 || item.status ==22" type="default"
                @click="endModal(item,'takeout',1)" :class="item.businessState<4?'open':'opens'">开仓取出</button>

              <button type="default"
                v-if="item.status == 0 || item.status == 1 || item.status == 5 || item.status == 10"
                @click="resultPop(item)" :class="item.businessState<4?'open':'opens'">取消订单</button>
              <button v-if="item.status == 1" type="default" @click="endModal(item,'takeCharge')"
                :class="item.businessState<4?'open':'opens'">发起充电</button>

              <button class="opens" v-if="item.status == 0" type="primary" @click="goPay(item)">去支付</button>
            </view>
          </view>
        </uni-card>

        <uni-popup ref="resultpop" type="center" :mask-click="true" :animation="false">
          <view class="result_box">
            <!-- <view class="checks" @click="checkSwitch">
              <uni-data-checkbox v-model="value" :localdata="range" selectedColor='#4ea7ff' :multiple="true"
                @change="checkcChange"></uni-data-checkbox>
              <text>是否放入电池</text>
            </view> -->
            <view class="checks">
              是否取消订单？
            </view>
            <view class="result_btn">
              <button type="default" class="reset" @click="closeResult">取消</button>
              <button type="default" @click="endCharge">确认</button>
            </view>
          </view>
        </uni-popup>

        <view v-show="isLoadMore && orderListing.length >0">
          <uni-load-more :status="loadStatus"></uni-load-more>
        </view>

        <view class="nodata" v-if="orderListing.length == 0">
          <image class="empty_img" src="/static/empty.png" mode="widthFix"></image>
          <view>没有你想要的内容</view>
        </view>

      </view>
    </view>
    <tabBar :current="3"></tabBar>

  </view>
</template>
<script>
  import moment from '../../components/moment.js';
  import {
    timekeeping
  } from '../../components/calculate/calculate.js';

  import {
    order,
    createOrder,
    createOrder2,
    charging
  } from '@/api/equip.js';
  import payjs from '@/pages/my/pay.js';
  import tabBar from "@/components/tabBar.vue";

  export default {
    mixins: [payjs],
    components: {
      tabBar: tabBar
    },
    data() {
      return {
        current: 0,
        values: ['进行中', '已完成'],
        orderListing: [],
        completed: [],
        parameters: {
          pageNumber: 0,
          pageSize: 50,
          searchCompleteStatus: ''
        },
        more: '',

        // 刷新
        triggered: true,
        loadDataTimings: '',
        timings: '',
        page: 1, //页码
        size: 5,
        loadStatus: 'loading', //加载样式：more-加载前样式，loading-加载中样式，nomore-没有数据样式
        isLoadMore: false, //是否加载中
        refresh: false, // 下拉刷新标示
        chargeType: { //计费模式
          'DURATION': '按时',
          'QUANTITY': '按电量'
        },
        fgFull: { //是否充满
          1: '已充满',
          0: '未充满'
        },
        value: [],
        range: [{
          "value": 0,
          "text": ""
        }],
        curOrderItem: {}, //当前点击的订单
      }
    },
    onShow() {
      // uni.hideTabBar();
      this.current = 0;
      this.loadDataTimings = '';
      this.timings = '';
      this.page = 1;
      this.orderListing = [];
      this.list();
    },

    methods: {
      list() {
        this.$Toast.loading('加载中');
        // queryStatus：1，进行中，2：已完成
        let dataParams = {
          pageNum: this.page,
          pageSize: this.size,
          queryStatus: this.current == 0 ? '1' : '2',
        };
        if (this.current == 1 && this.orderListing.length > 0) {
          dataParams.createTime = decodeURIComponent(this.orderListing[this.orderListing.length - 1].createTime);
        }

        createOrder('/changing/order/list', 'get', dataParams).then(res => {
          let datas = res.data.records;
          this.orderListing = this.page == 1 ? datas : this.orderListing.concat(datas);

          if (datas.length < this.size) { //小于size数，停止请求
            this.isLoadMore = true;
            this.loadStatus = 'nomore';
          } else {
            this.isLoadMore = false;
          }
        }).catch(error => {
          this.isLoadMore = false;
        }).finally(() => {
          uni.hideLoading();
          if (this.refresh) {
            uni.stopPullDownRefresh();
            this.refresh = false;
          }
        });
      },
      // 去支付
      goPay(item) {
        this.$Toast.loading('支付发起中...');
        charging('/order/pre/pay', 'get', {
          orderId: item.id
        }).then(res => {
          let wechatinfo = res.data;
          this.wechatPay(wechatinfo).then(succ => {}).catch(err => {
            if (err.errMsg == 'requestPayment:ok') { //支付成功
              this.$Toast.success('支付成功');
              setTimeout(() => {
                this.page = 1;
                this.orderListing = [];
                this.list();
              }, 1500)
            } else if (err.errMsg == 'requestPayment:fail cancel') { //用户取消
              this.$Toast.error('取消支付');
            } else {
              this.$Toast.error('支付失败');
            }
          });
        })
      },
      onPullDownRefresh() {
        this.refresh = true;
        this.page = 1;
        this.orderListing = [];
        this.list();
      },
      onReachBottom() {
        if (!this.isLoadMore) { //此处判断，上锁，防止重复请求
          this.isLoadMore = true;
          this.page++;
          this.list();
        }
      },
      checkcChange(e) {
        if (this.value.length == 0) {
          this.value = [0];
        } else {
          this.value = [];
        }
      },
      checkSwitch() {
        if (this.value.length == 0) {
          this.value = [0];
        } else {
          this.value = [];
        }
      },

      changeitem(e) {
        let clear = e.currentIndex == 0 ? this.orderListing : this.completed;
        clear.length = 0;
        this.current = e.currentIndex;
        this.page = 1;
        this.orderListing = [];
        this.list();
      },
      // 跳转订单详情
      charge(item) {
        let status = this.current == 0 ? '11' : '30';
        uni.navigateTo({
          url: `../charge/charge?orderId=${item.id}&createTime=${item.createTime}`
        })
      },
      // 结束订单弹框
      resultPop(item) {
        this.curOrderItem = item;
        this.$refs.resultpop.open();
      },
      // 关闭结束订单弹框
      closeResult() {
        this.$refs.resultpop.close();
      },
      // 结束充电按钮
      endModal(item, msg, type) {
        let cont = "";
        if (msg == 'takeout' && type == 1) { //开仓取出
          cont = '感谢您的使用，取出电池后请关好仓门。';
        } else if (msg == 'takeout' && type == 0) { //结束充电
          cont = '确定要结束充电吗？';
        } else if (msg == 'takeCharge') { //发起充电
          cont = '确定要发起充电吗？';
        }
        uni.showModal({
          title: '提示',
          content: cont,
          success: (modalRes) => {
            if (modalRes.confirm) {
              if (msg == 'takeout') {
                this.takeout(item, type);
              } else if (msg == 'takeCharge') {
                this.takeCharge(item);
              }
            } else if (modalRes.cancel) {

            }
          }
        })
      },
      // 开箱取出
      takeout(item, type) {
        let url = type == 1 ? '/open/door/get/battery' : '/stop/charging';
        let toast = type == 1 ? '正在开仓···' : '停止充电中···';
        let msg = type == 1 ? '开仓成功' : '充电已结束';
        this.$Toast.loading(toast);
        if (type == 1) {
          createOrder(url, 'get', {
              orderId: item.id
            }).then(res => {
              if (res.code == 200) {
                if (type == 1) {
                  if (res.data.needPay) { //需要支付
                    let wechatinfo = res.data.wxPrePayVO;
                    this.wechatPay(wechatinfo).then(succ => {}).catch(err => {
                      if (err.errMsg == 'requestPayment:ok') { //支付成功
                        uni.navigateTo({
                          url: '/pages/charge/charge?orderId=' + item.id
                        })
                      } else if (err.errMsg == 'requestPayment:fail cancel') { //用户取消
                        this.$Toast.error('取消支付');
                      } else {
                        this.$Toast.error('支付失败');
                      }
                    });
                  } else {
                    this.$Toast.success(msg);
                    setTimeout(() => {
                      uni.navigateTo({
                        url: '/pages/charge/charge?orderId=' + item.id
                      })
                    }, 1500)
                  }
                } else {
                  this.$Toast.success(msg);
                  setTimeout(() => {
                    this.page = 1;
                    this.orderListing = [];
                    this.list();
                  }, 1500)
                }
              }
            })
            .catch(err => {

            })
        } else {
          createOrder2(url, 'get', {
              orderId: item.id
            }).then(res => {
              if (res.code == 200) {
                this.$Toast.success(msg);
                setTimeout(() => {
                  this.page = 1;
                  this.orderListing = [];
                  this.list();
                }, 1500)
              }
            })
            .catch(err => {

            })
        }
      },
      // 结束订单
      endCharge() {
        this.$Toast.loading('订单结束中');
        let flag = this.value.length ? 1 : 0;
        createOrder('/charging/finish', 'get', {
          orderId: this.curOrderItem.id,
          flag: this.value.length ? 1 : 0
        }).then(res => {
          this.$refs.resultpop.close();
          if (res.code == 200) {
            this.$Toast.success('订单已结束');
            setTimeout(() => {
              this.page = 1;
              this.orderListing = [];
              this.list();
            }, 1500)
          }
        }).catch(err => {
          this.$refs.resultpop.close();
        })
      },
      // 发起充电
      takeCharge(item) {
        createOrder('/charging/again', 'get', {
          orderId: item.id
        }).then(res => {
          if (res.code == 200) {
            this.$Toast.success('发起充电成功');
            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/charge/charge?orderId=' + item.id
              })
            }, 1500)
          }
        })
      },

      onHide() {
        clearInterval(this.loadDataTimings);
        clearInterval(this.timings);
      },
      onUnload() {
        clearInterval(this.loadDataTimings);
        clearInterval(this.timings);
      },
      finish() {
        clearInterval(this.loadDataTimings);
        clearInterval(this.timings);
      },

      clickOne() {

      },

      /* 下拉被复位 */
      onRestore() {
        this.triggered = true; // 需要重置
      },
      /* 下拉被中止，没下拉完就松手就会触发 */
      onAbort() {

      },
    }
  }
</script>
<style>
  page {
    background-color: #f7f7f7;
  }
</style>
<style lang="scss" scoped>
  @import "@/static/css/main.scss";
  @import "@/static/css/common.scss";

  .content-body {
    padding-bottom: 160rpx;
  }

  .content-view {
    padding-bottom: 160rpx;
  }

  .tab {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 9;

    /deep/ .segmented-control {
      background-color: #1976d2;
    }

    /deep/ .segmented-control__item--text {
      border-bottom: 4px solid #ff9000;
      padding: 2px 12px !important;
      font-weight: bold;
    }

    /deep/ .segmented-control__text {
      font-size: 36rpx !important;
    }
  }

  .content {
    margin-top: 40upx;
  }

  .box {
    padding: 30upx 0;

    .title {
      font-size: 34rpx;
      color: #3a3a3a;
      font-weight: bold;
    }

    .time-box {
      margin-top: 30upx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #666666;
    }

    .order-date {
      display: flex;
      flex-direction: column;
      font-size: 24rpx;

      text {
        margin: 5upx 0;
      }
    }

    .order-time {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #858585;
    }

    .order-money {
      align-items: flex-end;
    }

    .billing-mode {
      margin-top: 12rpx;
      color: #858585;
      font-size: 24rpx;
    }

    .billing-rules {
      display: flex;
      justify-content: space-between;
      color: #858585;
      font-size: 24rpx;

      .billing-rules-left {
        display: flex;
        flex-direction: column;

        .status {
          color: #e24f4f;
        }

        .statuss {
          color: #858585;
        }

        view {
          margin: 10upx 0;
        }
      }
    }

    .bottom-button {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-top: 30upx;

      .end {
        width: 253upx;
        height: 71upx;
        color: #fff;
        background-color: #4ea7ff;
        line-height: 71upx;
        font-size: 24rpx;
      }

      .ends {
        width: 253upx;
        height: 71upx;
        color: #fff;
        background-color: #c2c2c2;
        line-height: 71upx;
        font-size: 24rpx;
      }

      .open {
        width: 253upx;
        height: 70rpx;
        color: #fff;
        background-color: #c2c2c2;
        line-height: 70rpx;
        font-size: 24rpx;
      }

      .opens {
        width: 210rpx;
        height: 72rpx;
        line-height: 72rpx;
        color: #fff;
        background-color: #4ea7ff;
        font-size: 24rpx;
        margin: 6rpx 10rpx;
      }
    }
  }

  // 刷新
  .scrollviewCss {
    overflow-y: hidden;
    height: 100vh;
  }

  button {
    margin: 0;
  }

  .result_box {
    width: 90%;
    height: 260rpx;
    background: #FFFFFF;
    border-radius: 24rpx;
    padding: 40rpx 60rpx;
    text-align: center;
    font-size: 36rpx;

    .checks {
      @include flexLayout(center, center);
      margin-top: 40rpx;
    }

    text {
      margin-left: -40rpx;
    }

    .result_btn {
      margin-top: 100rpx;
      @include flexLayout(center, space-between);

      button {
        width: 200rpx;
        height: 70rpx;
        line-height: 70rpx;
        margin: 0;
        background: #4ea7ff;
        color: #FFFFFF;
        font-size: 28rpx;
      }

      .reset {
        background: #D8D8D8;
      }
    }
  }

  button::after {
    border: none;
  }

  .labels {
    display: inline-block;
    width: 120rpx;
  }
</style>